import axios from "axios";
import { systemAppStore } from "@/stores/system";
import { userAppStore } from "@/stores/user";
import PsMessage from "@/components/message/index";
import { getTypeOf } from '@/utils'

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  headers: {
    "content-type": "application/json"
  },
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
});

// request interceptor
// 防止多次请求
// let startRefreshTokenFlag = false
service.interceptors.request.use(
  async (config) => {
    // do something before request is sent
    const appInfo = systemAppStore().appInfo || {};
    if (!config.noAppId && appInfo.appID) {
      config.headers["Version"] = appInfo.version;
      config.headers["UnionID"] = appInfo.channel;
      config.headers["AppId"] = appInfo.appID;
    }
    if (userAppStore().token) {
      config.headers["Authorization"] = "Bearer " + userAppStore().token;
      config.headers["Content-Type"] = "application/json";
    }
    return config;
  },
  (error) => {
    // do something with request error

    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    let data = response.data;
    const code = data?.code;
    const offset = response.config.xzconfig?.offset;
    if (!response.config.noTestCode && code !== 200) {
      if ([100403, 401].includes(code)) {
        userAppStore().resetUserInfo();
        userAppStore().login();
      } else if (!response.config.noMsg) {
        PsMessage({ offset, message: data.msg || "服务异常" });
      }
      return Promise.reject(data);
    } else {
      if(response.config.needRunHeaders){
        if(getTypeOf(data) !== 'object'){
          data = {
            data
          }
        }
        data['res_headers'] = response.headers
      }
      return data;
    }
  },
  (error) => {
    const { offset } = error.response?.config?.xzconfig || {};
    const code = error.response?.data?.code || error.response?.status;
    const msg = error.response?.data?.msg || error.message;
    if ([100403, 401].includes(code) && !error.response.config.noAutoLogin) {
      userAppStore().resetUserInfo();
      userAppStore().login();
    } else if (!error.config.noMsg && !axios.isCancel(error)) {
      if (msg === "Network Error") {
        PsMessage({ offset, message: "服务器连接异常，请检查网络！" });
      } else {
        PsMessage({ offset, message: msg || "服务异常" });
      }
    }
    return Promise.reject(error);
  }
);

export default service;
